# -*- coding: utf-8 -*-
"""
推荐系统控制层

负责处理商品推荐相关的HTTP请求和响应
"""
from fastapi import APIRouter, HTTPException, Depends, Query
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from typing import Optional
from app.services.recommendation_service import RecommendationService
from app.controllers.user_controller import get_current_user

# 创建路由
recommendation_router = APIRouter(
    prefix="/recommendations",
    tags=["recommendations"],
    responses={404: {"description": "Not found"}}
)

# HTTP Bearer token scheme
security = HTTPBearer()

# 初始化服务层
recommendation_service = RecommendationService()


@recommendation_router.get("/for-you")
async def get_recommendations_for_user(
    limit: int = Query(20, ge=1, le=50, description="推荐商品数量"),
    current_user = Depends(get_current_user)
):
    """获取个性化推荐商品（猜你喜欢）"""
    try:
        user_id = current_user.get('user_id')
        result = recommendation_service.get_recommendations_for_user(user_id, limit)
        
        if result['success']:
            return {
                "code": 200,
                "message": "获取推荐成功",
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取推荐失败: {str(e)}")


@recommendation_router.get("/similar/{goods_id}")
async def get_similar_goods(
    goods_id: str,
    limit: int = Query(10, ge=1, le=30, description="相似商品数量")
):
    """获取相似商品推荐"""
    try:
        result = recommendation_service.get_similar_goods(goods_id, limit)
        
        if result['success']:
            return {
                "code": 200,
                "message": "获取相似商品成功",
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取相似商品失败: {str(e)}")


@recommendation_router.get("/popular")
async def get_popular_goods(
    limit: int = Query(20, ge=1, le=50, description="热门商品数量")
):
    """获取热门商品"""
    try:
        result = recommendation_service.get_popular_goods(limit)
        
        if result['success']:
            return {
                "code": 200,
                "message": "获取热门商品成功",
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取热门商品失败: {str(e)}")


# =========================== UniApp 兼容接口 ===========================

# 创建UniApp兼容路由
uniapp_recommendation_router = APIRouter(
    prefix="/uniapp/recommendations",
    tags=["uniapp-recommendations"],
    responses={404: {"description": "Not found"}}
)

@uniapp_recommendation_router.get("/guess-you-like")
async def uniapp_get_guess_you_like(
    limit: int = Query(20, ge=1, le=50, description="推荐商品数量"),
    current_user = Depends(get_current_user)
):
    """UniApp获取猜你喜欢商品"""
    try:
        user_id = current_user.get('user_id')
        result = recommendation_service.get_recommendations_for_user(user_id, limit)
        
        if result['success']:
            return {
                "code": 200,
                "message": "获取推荐成功",
                "data": {
                    "goods_list": result['data']['recommendations'],
                    "total": result['data']['total_count'],
                    "algorithm_info": result['data']['algorithm_info']
                }
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取推荐失败: {str(e)}")


@uniapp_recommendation_router.get("/similar/{goods_id}")
async def uniapp_get_similar_goods(
    goods_id: str,
    limit: int = Query(10, ge=1, le=30, description="相似商品数量")
):
    """UniApp获取相似商品推荐"""
    try:
        result = recommendation_service.get_similar_goods(goods_id, limit)
        
        if result['success']:
            return {
                "code": 200,
                "message": "获取相似商品成功",
                "data": {
                    "goods_list": result['data']['similar_goods'],
                    "total": result['data']['total_count']
                }
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取相似商品失败: {str(e)}")


@uniapp_recommendation_router.get("/popular")
async def uniapp_get_popular_goods(
    limit: int = Query(20, ge=1, le=50, description="热门商品数量")
):
    """UniApp获取热门商品"""
    try:
        result = recommendation_service.get_popular_goods(limit)
        
        if result['success']:
            return {
                "code": 200,
                "message": "获取热门商品成功",
                "data": {
                    "goods_list": result['data']['popular_goods'],
                    "total": result['data']['total_count']
                }
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取热门商品失败: {str(e)}")


@uniapp_recommendation_router.get("/categories/{category_name}")
async def uniapp_get_category_recommendations(
    category_name: str,
    limit: int = Query(20, ge=1, le=50, description="推荐商品数量"),
    brand_name: Optional[str] = Query(None, description="品牌名称")
):
    """UniApp获取分类推荐商品"""
    try:
        # 使用推荐仓库直接获取分类商品
        goods_list = recommendation_service.recommendation_repo.get_goods_by_category(
            category_name, brand_name, None, limit
        )
        
        # 格式化商品信息
        formatted_goods = []
        for goods in goods_list:
            formatted_goods.append(recommendation_service._format_goods_info(goods))
        
        return {
            "code": 200,
            "message": "获取分类商品成功",
            "data": {
                "goods_list": formatted_goods,
                "total": len(formatted_goods),
                "category": category_name,
                "brand": brand_name
            }
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取分类商品失败: {str(e)}") 